//@ts-check
import store from '../store/index.js'

/**
 * 设置商品的选中状态(本地缓存)
 * @param {{ productId, sizeId }[]} arrProductInfo 商品ID
 * @param {0|1} status 选中与否状态
 */
export function setSelectProductGoodsLists(arrProductInfo, status) {
  /**
   * @type { SelectGoodsDatail[] }
   */
  let arrTemp = wx.getStorageSync('goto-shoppong-cart-arr-product-info');
  arrTemp = arrTemp ? arrTemp : [];
  arrProductInfo.forEach(productInfo => {
    let index = arrTemp.findIndex(v => v.productId === productInfo.productId && v.sizeId === productInfo.sizeId);
    if (status === 1 || status === 4) {
      index === -1 && arrTemp.push(productInfo);
    } else {
      arrTemp.splice(index, 1);
    }
  });
  (arrProductInfo.length === 0) && (arrTemp = []);

  wx.setStorage({
    data: arrTemp,
    key: 'goto-shoppong-cart-arr-product-info',
  })
}

/**
 * 获取当前用户的搜索记录的本地存储key值
 */
function getLocalSearchHistoryKey() {
  let userId = '0';
  if (store.state.userInfo !== null) {
    userId = store.state.userInfo.id;
  }
  return 'search-history-lists-' + userId;
}

/**
 * 获取本地缓存中的搜索记录
 */
export function getSearchHistory() {
  return wx.getStorageSync(getLocalSearchHistoryKey()) || [];
}

/**
 * 清空本地缓存中的搜索记录
 */
export function clearSearchHistory() {
  return wx.setStorageSync(getLocalSearchHistoryKey(), []);
}

/**
 * 清空本地缓存中的指定的搜索记录
 */
export function clearOneSearchHistory(index) {
  let preArrHistory = getSearchHistory();
  preArrHistory.splice(index, 1)
  return wx.setStorageSync(getLocalSearchHistoryKey(), preArrHistory);
}

/**
 * 追加本地缓存中的搜索记录数组
 */
export function addSearchHistory(txt) {
  let preArrHistory = getSearchHistory();
  let index = preArrHistory.indexOf(txt);
  if (index !== -1) {
    preArrHistory.splice(index, 1);
  }
  preArrHistory = [txt].concat(preArrHistory);
  wx.setStorageSync(getLocalSearchHistoryKey(), preArrHistory)
  return preArrHistory;
}